#include "SpaceShip.h"

#include "math.h"
#include "gamemath.h"
#include <stdlib.h>

#include "hge.h"
#include "hgesprite.h"
#include "hgeparticle.h"
#include "hgevector.h"

#include "gameobject.h"


SpaceShip::SpaceShip() : GameObject()
{
	Init();
}

SpaceShip::SpaceShip(Vector2D vec) : GameObject(vec)
{
	Init();
}

SpaceShip::SpaceShip(float _x, float _y) : GameObject(_x, _y)
{
	Init();
}

void SpaceShip::Init()
{
	speed = 0;
	speed_max = 3;

	direction = Vector2D(0, 1);

	acceleration = 4;
	radius = 64;

	destination = Vector2D();

	turn_rate = 0.07f;

	hull = 100;

	sprite = 0;
	pFuel = 0;

	type = typeSpaceShip;

	//pWeapon = new Weapon();
	//pWeapon->set_spaceship(this);
}

SpaceShip::~SpaceShip()
{

}

bool SpaceShip::Update(float _dt)
{
	if(destroy) return true; 

	if(hull <= 0)
		return true;

	//Processing position
	position += direction * speed;
 
	if(Vec2DLength(position - destination) > 1.0f)
	{
		//Processing direction
		direction += Vec2DNormalize(destination - position) * get_turnrate();
		direction.Normalize();
	}
	else
		destination = Vector2D(rand() % 800, rand() % 600);

	double lenght = Vec2DLength(destination - position);

	if(lenght > radius * speed_max)
		speed = min(speed + speed_max / acceleration + speed / acceleration, speed_max);
	else
		speed = lenght / radius;

	if(pFuel)
	{
		pFuel->MoveTo(position.x, position.y);
		pFuel->info.fSpeedMax = speed;
		pFuel->info.nEmission = (int)(speed * 90);
		pFuel->Update(_dt);
	}

	WrapAround(-32.0f, -32.0f, 832.f, 632.0f);

	return false;
}

void SpaceShip::WrapAround(int x1, int y1, int x2, int y2)
{
	if(position.x < x1)
		position.x = x2;
	if(position.x > x2)
		position.x = x1;
	if(position.y < y1)
		position.y = y2;
	if(position.y > y2)
		position.y = y1;

	//destroy = true;
}

bool SpaceShip::Render()
{
	if(destroy) return true;

	if(sprite)
		if(visible)
		{
			if(pFuel)
				pFuel->Render();
			
			sprite->RenderEx(position.x, position.y, -(float)atan2(direction.x, direction.y) + M_PI);
		}

	return false;
}